<template>
  <view class="max-w-md mx-auto full-screen flex flex-col">
    <view class="flex justify-between text-onSurface dark:text-onSurface-dark p-4">
      <view class="flex space-x-2 ml-2" @click="pickDateTime">
        <view>{{ date }}</view>
        <view>{{ weekday }}</view>
      </view>
      <view class="flex space-x-2" @click="chooseWeather">
        <view class="flex items-center">
          <text :class="[weatherIcon, 'size-4 bg-primary dark:bg-primary-dark rounded-full mr-2']" />
          <text>{{ weather }}</text>
        </view>
      </view>
    </view>
    <view class="border-t border-gray-200 dark:border-gray-600"></view>
    <view class="flex justify-between space-x-2 p-5">
      <view class="flex flex-col items-center" @click="mood = '开心'">
        <text class="i-mdi-emoticon-happy size-8" :class="mood === '开心' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark'" />
        <text>开心</text>
      </view>
      <view class="flex flex-col items-center" @click="mood = '生气'">
        <text class="i-mdi-emoticon-angry size-8" :class="mood === '生气' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark'" />
        <text>生气</text>
      </view>
      <view class="flex flex-col items-center" @click="mood = '平静'">
        <text class="i-mdi-emoticon-neutral size-8" :class="mood === '平静' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark'" />
        <text>平静</text>
      </view>
      <view class="flex flex-col items-center" @click="mood = '难过'">
        <text class="i-mdi-emoticon-cry size-8" :class="mood === '难过' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark'" />
        <text>难过</text>
      </view>
      <view class="flex flex-col items-center" @click="mood = '惊讶'">
        <text class="i-mdi-emoticon-frown size-8" :class="mood === '惊讶' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark'" />
        <text>惊讶</text>
      </view>
    </view>
    <view class="border-t border-gray-200 dark:border-gray-600"></view>
    <view class='box-border flex justify-between p-4' @tap="format">
      <view class="iconfont icon-charutupian" @tap="insertImage"></view>
      <view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
      <view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic"></view>
      <view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian" data-name="underline">
      </view>
      <view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1" data-name="header"
        :data-value="1"></view>
      <view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi" data-name="align"
        data-value="center"></view>
      <view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie" data-name="list"
        data-value="ordered"></view>
      <view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie" data-name="list"
        data-value="bullet"></view>
      <view class="iconfont icon-undo" @tap="undo"></view>
      <view class="iconfont icon-shanchu" @tap="clear"></view>
    </view>
    <view class="flex-1 relative mb-10">
      <editor id="editor" class="text-base leading-relaxed absolute inset-0" placeholder="开始输入..."
        show-img-size show-img-toolbar show-img-resize @statuschange="onStatusChange" @ready="onEditorReady">
      </editor>
    </view>
    <view class="sticky bottom-10">
      <button @click="addDiary" class="btn h-10 mx-8 rounded-full" hover-class="btn-hover">添加</button>
    </view>
    <tui-datetime ref="dateTime" :type="2" @confirm="changeDateTime" :color="$theme.primary()"
      :bodyBackground="$theme.surface()" :headerBackground="$theme.surface()" :headerTextColor="$theme.onSurface()"
      :headerTextStyle="$theme.onSurface()"></tui-datetime>
    <tui-modal :show="weatherModal" @cancel="closeWeather" :backgroundColor="$theme.surface()" custom>
      <view class="flex justify-center items-center space-x-4">
        <view class="text-center" @click="selectWeather('晴')">
          <text
            :class="['i-mdi-white-balance-sunny size-6', weather === '晴' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark']" />
          <br />
          <text
            :class="weather === '晴' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark'">
            晴</text>
        </view>
        <view class="text-center" @click="selectWeather('阴')">
          <text
            :class="['i-mdi-weather-partly-cloudy size-6', weather === '阴' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark']" />
          <br />
          <text
            :class="weather === '阴' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark'">
            阴</text>
        </view>
        <view class="text-center" @click="selectWeather('雨')">
          <text
            :class="['i-mdi-weather-pouring size-6', weather === '雨' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark']" />
          <br />
          <text
            :class="weather === '雨' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark'">
            雨</text>
        </view>
        <view class="text-center" @click="selectWeather('雪')">
          <text
            :class="['i-mdi-weather-snowy size-6', weather === '雪' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark']" />
          <br />
          <text
            :class="weather === '雪' ? 'text-primary dark:text-primary-dark' : 'text-onSurface dark:text-onSurface-dark'">
            雪</text>
        </view>
      </view>
    </tui-modal>
  </view>
</template>

<script lang="ts" setup>
import tui from "@/common/httpRequest"
import tuiDatetime from "@/components/thorui/tui-datetime/tui-datetime.vue"
import tuiModal from "@/components/thorui/tui-modal/tui-modal.vue"
import utils from "@/utils/util"

const instance = getCurrentInstance();
const $theme = instance?.appContext.config.globalProperties.$theme;

// 验证登录
const isLogin = () => {
  const openid = uni.getStorageSync('openid');
  if (!openid) {
    uni.navigateTo({
      url: '/pages/auth/login'
    });
  }
}

onLoad(() => {
  isLogin()
})

const today = new Date()
const date = ref(utils.formatDate(today, 'YYYY年MM月DD日'))
const weekday = ref(utils.getWeekday(today))
const mood = ref('开心')

const dateTime: any = ref();
const pickDateTime = () => {
  dateTime.value?.show();
};
const changeDateTime = (e: any) => {
  const d = new Date(e.result)
  date.value = utils.formatDate(d, 'YYYY年MM月DD日')
  weekday.value = utils.getWeekday(d)
}

const weatherModal = ref(false);
const weather = ref('晴');
const weatherIcon = ref('i-mdi-white-balance-sunny');
const closeWeather = () => {
  weatherModal.value = false;
};
const chooseWeather = () => {
  weatherModal.value = true;
};
const selectWeather = (data: string) => {
  weatherModal.value = false;
  weather.value = data;
  switch (data) {
    case '晴':
      weatherIcon.value = 'i-mdi-white-balance-sunny';
      break;
    case '阴':
      weatherIcon.value = 'i-mdi-weather-partly-cloudy';
      break;
    case '雨':
      weatherIcon.value = 'i-mdi-weather-pouring';
      break;
    case '雪':
      weatherIcon.value = 'i-mdi-weather-snowy';
      break;
  }
};

interface Format {
  bold?: boolean;
  italic?: boolean;
  underline?: boolean;
  strike?: boolean;
  align?: string;
  color?: string;
  backgroundColor?: string;
  list?: string;
  header?: number;
  script?: string;
  direction?: string;
}

const formats = ref<Format>({
  bold: false,
  italic: false,
  underline: false,
  strike: false,
  align: '',
  color: '',
  backgroundColor: '',
  list: '',
  header: undefined,
  script: '',
  direction: ''
});
let editorCtx: any = null;

const addDiary = () => {
  editorCtx.getContents({
    success: (r: any) => {
      // 验证内容是否为空
      if (r.text.trim() === '') {
        tui.toast('请输入内容');
        return;
      }
      const html = r.html;
      const images: string[] = html.match(/<img[^>]*>/g);
      const srcs: string[] = images?.map(img => img.match(/src="([^">]+)"/)?.[1] ?? '');

      const diary: DiaryModel = {
        day: date.value.replace('年', '-').replace('月', '-').replace('日', ''),
        weather: weather.value,
        mood: mood.value,
        content: r.html
      }
      if (Array.isArray(srcs) && srcs.length > 0) {
        const uploadPromises = srcs.map((src) => {
          return tui.uploadFile('/diary/upload_img', src).then((res: any) => {
            if (res.code === 0) {
              return res.data;
            } else {
              throw new Error(`Failed to upload image: ${src}`);
            }
          });
        });

        Promise.all(uploadPromises)
          .then((urls) => {
            urls.forEach((url, index) => {
              diary.content = diary.content.replace(srcs[index], url);
            });
            return tui.request(`/diary/add`, 'POST', diary, true, false, false);
          })
          .then((res: any) => {
            if (res.code === 0) {
              tui.toast('添加成功');
            } else {
              tui.toast('添加失败');
            }
          })
          .catch((error) => {
            console.error('Error during upload or request:', error);
            tui.toast('上传或请求失败');
          });
      } else {
        tui.request(`/diary/add`, 'POST', diary, true, false, false).then((res: any) => {
          if (res.code === 0) {
            tui.toast('添加成功');
          } else {
            tui.toast('添加失败');
          }
        });
      }
    }
  })
};

const onEditorReady = () => {
  uni.createSelectorQuery().select('#editor').context((res) => {
    if (res && !Array.isArray(res) && res.context) {
      editorCtx = res.context;
    }
  }).exec();
};

const undo = () => {
  editorCtx?.undo();
};

const format = (e: Event) => {
  const { name, value } = (e.target as HTMLElement).dataset;
  if (!name) return;
  editorCtx?.format(name, value);
};

const onStatusChange = (e: any) => {
  formats.value = e.detail;
};

const clear = () => {
  uni.showModal({
    title: '清空编辑器',
    content: '确定清空编辑器全部内容？',
    success: (res) => {
      if (res.confirm) {
        editorCtx?.clear({
          success: () => console.log("clear success")
        });
      }
    }
  });
};

const insertImage = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      editorCtx.getContents({
        success: (r: any) => {
          const html = r.html
          // 查询html中的<img>标签数量
          const images = html.match(/<img[^>]*>/g);
          if (images && images.length == 3) {
            uni.showToast({
              title: '最多上传3张图片',
              icon: 'none',
              duration: 2000
            });
            return;
          }
          if (Array.isArray(res.tempFiles) && res.tempFiles.length > 0) {
            const file = res.tempFiles[0];
            const maxSize = 2024 * 1024; // 2MB
            if (file.size > maxSize) {
              uni.showToast({
                title: '图片大小不能超过2MB',
                icon: 'none',
                duration: 2000
              });
              return; // 停止上传
            }
          }
          editorCtx?.insertImage({
            src: res.tempFilePaths[0],
            alt: '',
            success: () => console.log('insert image success')
          });
        }
      });
    }
  });
};

</script>

<style lang="scss" scoped>
@use "../../static/style/btn.scss";
@import "./editor-icon.css";

.iconfont {
  display: inline-block;
  padding: 8px 8px;
  width: 24px;
  height: 24px;
  cursor: pointer;
  font-size: 20px;
}

.toolbar {
  box-sizing: border-box;
  border-bottom: 0;
  font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
}

.ql-container {
  box-sizing: border-box;
  padding: 12px 15px;
  width: 100%;
  min-height: 30vh;
  height: 100%;
  font-size: 16px;
  line-height: 1.5;
}

.ql-active {
  color: #06c;
}
</style>